import { setCookie } from '@/utils/cookie/cookie'

export default {
    namespace: 'token',
    state: {
        token: '',
        userId: '',
        userName: '',
        identity: '',
    },
    effects: {
        *changeState({ token, userId, userName, identity }, { put }) {
            if (token !== null && token !== undefined) {
                yield put({
                    type: 'changeOneState',
                    field: 'token',
                    data: token
                })
            }
            if (userId !== null && userId !== undefined) {
                yield put({
                    type: 'changeOneState',
                    field: 'userId',
                    data: userId
                })
            }
            if (userName !== null && userName !== undefined) {
                yield put({
                    type: 'changeOneState',
                    field: 'userName',
                    data: userName
                })
            }
            if (identity !== null && identity !== undefined) {
                yield put({
                    type: 'changeOneState',
                    field: 'identity',
                    data: identity
                })
            }
        }
    },
    reducers: {
        changeOneState(state, { field, data }) {
            const nextState = JSON.parse(JSON.stringify({ data: state })).data
            nextState[field] = data
            const keys = Object.keys(nextState)
            setCookie(field, data, 1)
            return nextState
        }
    }
}
